# 读取历史记录
import json
import os
import sys
from datetime import datetime
from collections import deque

from PyQt6.QtWidgets import QMessageBox

from utils.error import getError
from utils.index import resource_path
from front.actions.setting import update_setting


def get_history(win, func):
    # 打开 JSON 文件
    with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:
        data = json.load(file)  # 读取文件内容并解析为 Python 对象
        if not data["history_path"] or data["history_path"] == 'None':
            # 需要先判断data["history_path"]的数据长度是否为0，如果为零则提示没有历史记录
            # win.ui.setting = HistoryPath()
            # win.ui.history_path.show()
            update_setting(win)
        else:
            try:
                with open(data["history_path"], 'r', encoding='utf-8') as file:
                    history_data = json.load(file)
                    item_history_data = history_data.get(win.e_name, [])
                    if len(item_history_data) > 0:  # 当历史记录不为空时，打开设置历史路径的窗口
                        win.ui.history_ui = func(data["history_path"], win)
                        win.ui.history_ui.show()
                    else:
                        QMessageBox.critical(win, f'SeismicPlot-{win.module_name}历史记录', '暂无历史记录',
                                             QMessageBox.StandardButton.Ok)
            except Exception as e:
                # 捕获异常并显示错误信息
                err = getError()
                QMessageBox.critical(win, f"{err['type']}",
                                     f"{err['msg']}, file in {err['file']}, line in {err['line']}.")


# 写入历史记录
def setHistory(win, status):
    # 读取配置文件
    with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:
        setting = json.load(file)  # 读取文件内容并解析为 Python 对象

    if setting["history_path"] == "None":
        # 获取可执行文件所在的目录
        if getattr(sys, 'frozen', False):
            # 如果是打包后的可执行文件
            application_path = os.path.dirname(sys.executable)
        else:
            # 如果是脚本运行
            # application_path = os.path.dirname(os.path.abspath(__file__))
            application_path = r"D:\myFile\appDev"
        data_list = {
            "bridge": [],
            "mul_wave": [],
            "inclinedShaft": [],
            "joint_well": []
        }
        path = os.path.join(application_path, 'historyList.json')
        try:
            # 重新生成历史记录文件
            with open(path, 'w', encoding='utf-8') as file:
                json.dump(data_list, file, indent=4)
            # 将运行参数等信息，保存到历史记录文件中
            write_history(win, path, status)
            # 修改setting.json中记录的历史记录文件的路径
            with open(resource_path("static/json/setting.json"), 'r', encoding='utf-8') as file:  # 读取设置文件
                data = json.load(file)
            arr = path.split('\\')
            path = "/".join(arr)
            data["history_path"] = path
            with open(resource_path("static/json/setting.json"), 'w', encoding='utf-8') as file:  # 修改设置文件
                json.dump(data, file, indent=4)
            QMessageBox.information(win, '操作成功', f'成功将历史记录文件保存到{path}！',
                                    QMessageBox.StandardButton.Ok)
        except:
            err = getError()
            QMessageBox.critical(win, f"{err['type']}", f"{err['msg']}", QMessageBox.StandardButton.Ok)
    elif setting["history_path"]:  # 如果历史文件路径存在
        try:
            write_history(win, setting["history_path"], status)
        except json.JSONDecodeError as e:  # 当写入错误时
            data_list = {
                "bridge": [],  # 桥图
                "mul_wave": [],  # 多次波
                "inclinedShaft": [],  # 桥图|斜井
                "joint_well": []  # 联井
            }
            # 重新生成历史记录文件
            with open(setting["history_path"], 'w', encoding='utf-8') as file:
                json.dump(data_list, file, indent=4)
            write_history(win, setting["history_path"], status)


# 将运行参数和其他信息写入历史记录文件中
def write_history(win, path, status):
    with open(path, 'r', encoding='utf-8') as file:
        history_data = json.load(file)
        item_history_data = history_data.get(win.e_name, [])

        # title
        arr = win.params["outfile"].split('/')
        arr2 = arr[len(arr) - 1].split('.')
        arr2.pop()
        title = ".".join(arr2)

        # date_time
        current_time = datetime.now()
        date_time = current_time.strftime("%Y:%m:%d %H:%M:%S")

        # 历史记录对象
        data = {
            "title": title,  # 标题
            "status": status,  # 状态
            "date_time": date_time,  # 日期
            "data": win.params  # 参数
        }

        # 时间复杂度为 O(1)，在频繁在列表头部插入元素的场景下，性能更优
        my_deque = deque(item_history_data)
        my_deque.appendleft(data)
        history_data[win.e_name] = list(my_deque)

    # 将更新后的数据写入历史记录文件中
    with open(path, 'w', encoding='utf-8') as file:
        json.dump(history_data, file, indent=4)